<?php
namespace app\interfaces\controller;

use app\interfaces\model\MemberIntegral as MemberIntegralModel;
use app\interfaces\model\IntegralGoods as IntegralGoodsModel;
use app\interfaces\model\Member as MemberModel;
use app\interfaces\model\IntegralRecord as IntegralRecordModel;
use app\interfaces\model\MemberAddress as MemberAddressModel;
use think\Request;
use think\Db;
use think\Exception;

class IntegralGoods
{

    /*
     * 用户端 - 积分商品列表
     * @param  string $user_id 会员ID
     */
    public function integral_list()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');

        if (empty($user_id)) throw new Exception('not Empty');

        $model = new IntegralGoodsModel();

        // 读取列表
        $result = $model->field('id,title,number,picUrl,price')
            ->order(['sort' => 'desc','id'=>'desc'])
            ->paginate(6);

        // 地址
        $address = MemberAddressModel::where(['member_id' => $user_id])
            ->field('name,phone,address,area_info')
            ->order(['status' => 'asc', 'create_time' => 'desc'])
            ->find();

        if (empty($address)) $address = '';

        // 积分
        $integral = MemberModel::where(['id' => $user_id])->value('integral');
        is_null($integral) ? $integral = 0 : $integral = $integral;
        return ['code' => 200, 'message' => '成功', 'data' => $result, 'integral' => $integral, 'address' => $address];
    }

    /*
     * 用户端 - 积分兑换
     * @param  string $user_id          会员ID
     * @param  string $name             姓名
     * @param  string $phone            手机号
     * @param  string $area_info        区域
     * @param  string $address          详细地址
     * @param  string $goods_id         商品ID
     * @param  string $title            标题
     * @param  string $number           数量
     * @param  string $picUrl           图片
     */
    public function integral_conversion()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['user_id']) || empty($data['name']) || empty($data['phone']) || empty($data['area_info']) || empty($data['address']) || empty($data['goods_id']) || empty($data['title']) || empty($data['number']) || empty($data['picUrl'])) throw new Exception('not Empty');

        // 启动事务
        Db::startTrans();
        try {

            // 读取会员积分 和 商品需要积分
            $find = Db::name('member')->where(['id' => $data['user_id']])->value('integral');
            $integral = Db::name('integral_goods')->where(['id' => $data['goods_id']])->field('price,number')->find();

            if ($find < ($integral['price'] * $data['number'])) return ['code' => 402, 'message' => '积分不足,无法兑换'];

            if ($integral['number'] < $data['number']) return ['code' => 402, 'message' => '剩余数量不足,无法兑换'];

            $information = [
                'member_id'   => $data['user_id'],
                'name'        => $data['name'],
                'phone'       => $data['phone'],
                'area_info'   => $data['area_info'],
                'address'     => $data['address'],
                'goods_id'    => $data['goods_id'],
                'title'       => $data['title'],
                'number'      => $data['number'],
                'picUrl'      => $data['picUrl'],
                'integral'    => $integral['price'],
                'status'      => '1',
                'create_time' => time()
            ];

            // 添加
            Db::name('member_integral')->insert($information);

            // 扣除积分
            Db::name('member')->where(['id' => $data['user_id']])->setDec('integral', $integral['price']);

            // 扣除库存
            Db::name('integral_goods')->where(['id' => $data['goods_id']])->setDec('number', $data['number']);

            // 添加记录
            Db::name('integral_record')->insert(
                [
                    'member_id'   => $data['user_id'],
                    'type_id'     => '2',
                    'type'        => '兑换',
                    'integral'    => $integral['price'],
                    'title'       => '兑换' . $data['title'],
                    'create_time' => time()
                ]
            );

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }
    }

    /*
     * 用户端 - 积分明细列表
     * @param  string $user_id 会员ID
     */
    public function integral_detail()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $type = Request::instance()->param('type', '1');

        if (empty($user_id)) throw new Exception('not Empty');

        // 搜索条件
        $condition['member_id'] = ['eq', $user_id];

        // 条件
        if (!empty($type)) $condition['type_id'] = ['eq', $type];


        $model = new IntegralRecordModel();

        // 读取列表
        $result = $model->where($condition)
            ->field('id,type_id,title,integral,create_time')
            ->order(['id' => 'desc'])
            ->paginate(10);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }


    // 确认收货
    public function confirm_order()
    {
        if (Request::instance()->isPost()) {
            // 获取参数
            $id = Request::instance()->param('id');
            if (empty($id)) throw new Exception('not Empty');

            // 模型实例化
            $model = new MemberIntegralModel();

            // 改变状态
            $operation = $model->save(['status'=>3],['id'=>$id]);

            if ($operation) {
                return ['code'=>200,'message'=>'成功'];
            }else{
                return ['code'=>401,'message'=>'失败'];
            }
        }


    }



    // 积分订单列表
    public function goods_list()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');
        if (empty($user_id)) throw new Exception('not Empty');

        // 模型实例化
        $model = new MemberIntegralModel();

        $data = $model->where(['member_id'=>$user_id])->field('id,picUrl,title,number,create_time,status,express_value,tracking_number,integral')->paginate(10,false);



        return ['code'=>200,'message'=>'成功','data'=>$data];

    }




}
